﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Web;
using WinFormClient.ServiceReference1;

namespace WinFormClient
{
    public partial class MainForm : Form
    {
        #region (窗口透明代码)
        [StructLayout(LayoutKind.Sequential)]
        public struct MARGINS
        {
            public int Left;
            public int Right;
            public int Top;
            public int Bottom;
        }

        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern bool DwmIsCompositionEnabled();

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            return;
            if (DwmIsCompositionEnabled())
            {
                MARGINS margins = new MARGINS();
                margins.Right = margins.Left = margins.Top = margins.Bottom = this.Width + this.Height;
                DwmExtendFrameIntoClientArea(this.Handle, ref margins);
            }

        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);
            return;
            if (DwmIsCompositionEnabled())
            {
                e.Graphics.Clear(Color.Black);
            }
        }
        #endregion
        public Client client;
        Group selectedgroup;
        int currenttopicpage;
        Dictionary<int, ChatForm> openedForms;
        public MainForm(Client c)
        {
            InitializeComponent();
            this.client = c;
            client.TopicsPerPage = 25;
            //读取Groups
            client.FinishedLoadGroup += new EventHandler(client_FinishedLoadGroup);
            //样例代码 此处关键! 添加Finished***事件的处理函数
            client.FinishedLoadTopic += new EventHandler(client_FinishedLoadTopic);
            client.ShowErrorMsg += new EventHandler(client_ShowErrorMsg);
            openedForms = new Dictionary<int, ChatForm>();
            client.FetchGroups();
        }

        void client_ShowErrorMsg(object sender, EventArgs e)
        {
            MessageBox.Show(sender.ToString());
            //throw new NotImplementedException();
        }
        //绘制group
        void client_FinishedLoadGroup(object sender, EventArgs e)
        {
            GroupSet groups = sender as GroupSet;
            foreach (Group group in groups.Groups)
            {
                GroupWith2String g = new GroupWith2String(group);
                LbxGroup.Items.Add(g);
            }
        }

        // 此处代表已经加载完成，object sender里的内容即为返回的数据
        void client_FinishedLoadTopic(object sender, EventArgs e)
        {
            LbxTopics.Items.Clear();
            TopicSet topics = sender as TopicSet;
            this.Text = topics.Topics.Length.ToString();
            foreach (Topic topic in topics.Topics)
            {
                TopicWith2String t = new TopicWith2String(topic);
                LbxTopics.Items.Add(t);
            }
            int page = topics.group.topicCnt / 25 + 1;
            LbSumPages.Text = "/" + page.ToString();
            //throw new NotImplementedException();
        }
        /*
        //样例代码 加载topic时候这样调用就好
        private void button1_Click(object sender, EventArgs e)
        {
            client.FetchTopics(0);
        }*/

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            client.Exit();
            Application.Exit();//确保整个程序退出 不然登录窗口还在那里隐藏着呢
        }
        //展开topics
        private void LbxGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedgroup = LbxGroup.Items[LbxGroup.SelectedIndex] as Group;
            currenttopicpage = 1;
            Pagejumper(0);           
        }
        //跳页
        private void Pagejumper(int jumpnum)
        {
            int pagecount;
            int.TryParse(LbSumPages.Text.Substring(1), out pagecount);
            //LbSumPages.Text="/"+topiccount;
            if ((currenttopicpage + jumpnum >= 1) && (currenttopicpage + jumpnum <= pagecount)||jumpnum==0)
            {
                client.FetchTopics(selectedgroup.id, jumpnum + currenttopicpage);
                TxtTopicPage.Text = (jumpnum + currenttopicpage).ToString();
            }
            else MessageBox.Show(jumpnum.ToString()+currenttopicpage.ToString());
        }
        //绘制topic
        private void LbxTopics_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush br;
            int r;
            Math.DivRem(e.Index, 2, out r);
            if (r == 0)
                br = Brushes.White;
            else
                br = Brushes.AliceBlue;
            e.DrawBackground();
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                e.DrawFocusRectangle();

            Brush b = Brushes.Black;
            e.Graphics.FillRectangle(br, e.Bounds);
            e.Graphics.DrawString(this.LbxTopics.Items[e.Index].ToString(), this.LbxTopics.Font, b, e.Bounds);
        }

        private void LlbPageBefore_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Pagejumper(-1);
        }

        private void LlbPageAfter_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Pagejumper(1);
        }

        private void BtnPageJump_Click(object sender, EventArgs e)
        {
            try
            {
                int page = Int32.Parse(TxtTopicPage.Text);
                Pagejumper(page - currenttopicpage);
            }
            catch { TxtTopicPage.Clear(); }
        }

        private void BtnNewTopic_Click(object sender, EventArgs e)
        {
            client.AddTopic(TxtNewTopic.Text, selectedgroup.id);
        }

        private void LbxTopics_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void LbxTopics_DoubleClick(object sender, EventArgs e)
        {
            if (LbxTopics.SelectedIndex == -1) return;
            Topic selectedtopic = LbxTopics.Items[LbxTopics.SelectedIndex] as Topic;
            ChatForm Chatter;
            openedForms.TryGetValue(selectedtopic.id, out Chatter);
            if (Chatter == null)
            {
                Chatter = new ChatForm(selectedtopic, client);
                openedForms.Add(selectedtopic.id, Chatter);
            }
            Chatter.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] s = textBox1.Text.Split(',');
            int a = int.Parse(s[0]);
            int b = int.Parse(s[1]);
            client.FetchTopics(selectedgroup.id, a, b);
        }
    }
    public class GroupWith2String : Group
    {
        public override string ToString()
        {
            return this.name;
        }
        public GroupWith2String(Group f)
        {
            this.name = f.name;
            this.id = f.id;
            this.topicCnt = f.topicCnt;
        }
    }
    public class TopicWith2String : Topic
    {
        public override string ToString()
        {
            return this.title;
        }
        public TopicWith2String(Topic t)
        {
            this.groupId = t.groupId;
            this.id = t.id;
            this.title = t.title;
            this.idInGroup = t.idInGroup;
        }
    }
}
